package com.write;

import com.domain.WriteData;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.pdf.utils.PDFUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;

/**
 * 处理简单的字符串写入pdf类
 */
public class DefaultWriteData implements WriteDataHandle {
    @Override
    public void write(Document document, WriteData writeData, Map<String, PdfPTable> pdf_table_map, String previousGroup) {
        try {
            String row = writeData.getRow();
            String group = writeData.getGroup();
            float[] cellSizeArray = writeData.getCellSizeArray();
            Font font = writeData.getFont().getFont(writeData.getTextLevEnum());

            if (!StringUtils.isEmpty(row) && !StringUtils.isEmpty(group)) {
                PdfPTable pdfPTable = pdf_table_map.get(group);
                if (Objects.isNull(pdfPTable)) {
                    if (ArrayUtils.isNotEmpty(cellSizeArray)) {
                        pdfPTable = PDFUtils.createPdfTable(Integer.valueOf(row), cellSizeArray);
                    }else {
                        pdfPTable = PDFUtils.createPdfTable(Integer.valueOf(row), null);
                    }

                    pdf_table_map.put(group, pdfPTable);
                }
                if (writeData.getChangeCellSizeBoolean()) {
                    PDFUtils.addNoBorderCell(pdfPTable, writeData, font, writeData.getAlignment());
                    return;
                }
                PDFUtils.addNoBorderCell(pdfPTable, value(writeData), font, writeData.getAlignment());
                return;

            }

            Paragraph paragraph = new Paragraph(writeData.getStringValue(), font);
            paragraph.setAlignment(writeData.getAlignment().getAlignment()); //设置文字居中 0靠左   1，居中     2，靠右
            paragraph.setIndentationLeft(0); //设置左缩进
            paragraph.setIndentationRight(0); //设置右缩进
            paragraph.setFirstLineIndent(0); //设置首行缩进
            paragraph.setLeading(10f); //行间距
            paragraph.setSpacingBefore(15F); //设置段落上空白
            paragraph.setSpacingAfter(20f); //设置段落下空白
            PDFUtils.addLine(document, writeData.getLineEnum(), paragraph);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String value(WriteData writeData) {
        return org.apache.commons.lang3.StringUtils.join(writeData.getKey(), ": ", writeData.getStringValue());
    }

}
